<?php
#                                                                                 
# author: Cody Sorgenfrey                                       
# (c)2013 South Hill Calvary Chapel                                               
#    
include_once("../mysql/database_info.php");
include_once("common.php");
include_once("../mysql/common.php");
connect_select_test("ministryApps");
function postToDB()
{
	$testQuery = "SELECT * FROM `appReplies`";
	$testReply = mysql_num_fields(mysql_query($testQuery));
	$numQuestions = $testReply-8;
	if ($numQuestions < (count($_POST)-6)){
		$difference = (count($_POST)-6) - $numQuestions;
		$addFields = "ALTER TABLE `appReplies` ADD (";
		for ($x=1;$x<=$difference;$x++){
			$questionNumber = $numQuestions + $x;
			if ($x == $difference){	
				$addFields .= "`$questionNumber` text)";
			} else {
				$addFields .= "`$questionNumber` text,\n ";
			}
		}
		$x = mysql_query($addFields);
		if (!$x){
			printf("<script type='text/javascript'>alert(\"Error! Query: %s\")</script>\n", $addFields);
			printf("%s", mysql_error());
			return 0;
		}
		postToDB();
	} else {
		$query = "INSERT INTO `appReplies`";
		$query .= " VALUES('','".$_REQUEST['ministry']."', ";
		$query .= "'".$_POST['fname']."', ";
		$query .= "'".$_POST['lname']."', ";
		$query .= "'".$_POST['age']."', ";
		$query .= "'".$_POST['homePhone']."', ";
		$query .= "'".$_POST['cellPhone']."', ";
		$query .= "'".$_POST['email']."', ";
		for ($x=0;$x<($testReply-8);$x++){
			if ($x==($testReply-9)){
				$query .= "'".$_POST["$x"]."')";
			} else {
				$query .= "'".$_POST["$x"]."', ";
			}
		}
		$x = mysql_query($query);
		if (!$x){
			printf("<script type='text/javascript'>alert(\"Error! Query: %s\")</script>\n", $query);
		}
	}
}
function question($question, $index, $ministry)
{
	printf("\t\t\t<div class='question'>\n");
	printf("\t\t\t\t<h4 class='text'>\n");
	printf("\t\t\t\t\t%s\n", $question);
	printf("\t\t\t\t</h4>\n");
	if ($ministry["$index-type"] == "text"){
		printf("\t\t\t\t<textarea style='' name='%s'>%s</textarea><br><br>", $index, $_POST[$index]);
	} else if ($ministry["$index-type"] == "short"){
		printf("\t\t\t\t<input type='text' style='width:%s' name='%s' value='%s'><br><br>", "98%", $index, $_POST[$index]);
	} else if (stristr($ministry["$index-type"], "check\n")){
		$opts = explode("\n", $ministry["$index-type"]);
		for ($x=1;$x<count($opts);$x++){
			printf("\t\t\t\t<input type='checkbox' name='%s' value='%s'> %s<br>", $index, $opts[$x], $opts[$x]);
			if ($x == count($opts)-1){
				printf("<input type='hidden' name='%s'><br>", $index);
			}	
		}	
	} else if (stristr($ministry["$index-type"], "radio\n")){
		$opts = explode("\n", $ministry["$index-type"]);
		for ($x=1;$x<count($opts);$x++){
			printf("\t\t\t\t<input type='radio' name='%s' value='%s'> %s<br>", $index, $opts[$x], $opts[$x]);
			if ($x == count($opts)-1){
				printf("<br>");
			}	
		}
	}
	printf("\t\t\t</div>\n");
}
$meta_key='app, worship, team, apply, try out, worship team, praise';
$meta_desc="The ministry team's applications at South Hill Calvary Chapel.";
$morejava ="<style type='text/css'>
	textarea {
		width:98%;
		height: 100px;
	}
</style>
<script type='text/javascript'>
	var timer = null;
	function validateEmail(obj)  	
	{
		window.clearTimeout(timer);
		timer = setTimeout(function(){
			if (obj.value.search(/.+@.+\..+/) == -1){ 
				obj.style.outline = '1px solid red';
				return 1; 
			} else {
				obj.style.outline = 'none';
				return 0;
			}
		}, 1000);	
	}
	function customSubmit(form)
	{
		var notComplete = validateEmail(document.getElementsByTagName('input')[5]);
		$(document).ready(function(){
			$(':input').css('outline', 'none');
			$(':input').each(function(){
				 if ($(this).attr('type') == 'radio'){
					var names = $(this).attr('name');
					if (!$(':input[name='+names+']:checked').length){
						$(this).css('outline', '1px solid red');
						notComplete = 1;
					}
				} else if ($(this).attr('type') == 'checkbox'){
					var names = $(this).attr('name');
					if (!$(':input[name='+names+']:checked').length){
						$(this).css('outline', '1px solid red');
						notComplete = 1;
					} else {
						var newVal = '';
						$(':input[name='+names+']:checked').each(function(){
							newVal += $(this).val() + ', ';
						});
						$(':input[name='+names+'][type=hidden]').val(newVal);
						$(':input[name='+names+'][type=hidden]').attr('name', names);
					}
				} else {
					if ((($(this).val() == '') || ($(this).val() == null)) && ($(this).attr('name') != 'homePhone') && ($(this).attr('name') != 'cellPhone')){
						$(this).css('outline', '1px solid red');
						notComplete = 1;
					}
				}
			});
		});
		if (notComplete){
			document.getElementById('incomplete').innerHTML = 'Some fields are incomplete. Please fill out incomplete fields and try again.';
			$(document).ready(function(){
			});
		} else {
			$(':input[type=checkbox]').attr('disabled', 'true');
			form.submit();
		}
	}
	function nextQ(obj)
	{
		obj.parentNode.style.webkitTransform = 'translateX(-1000px)';
		setTimeout(function(){
			obj.parentNode.style.display = 'none';
		}, 1000);
		obj.parentNode.nextSibling.nextSibling.style.display = 'block';
		setTimeout(function(){
			obj.parentNode.nextSibling.nextSibling.style.webkitTransform = 'translateX(0px)';
		}, 700);
	}
	function prevQ(obj)
	{
		obj.parentNode.style.webkitTransform = 'translateX(1000px)';
		setTimeout(function(){
			obj.parentNode.style.display = 'none';
			obj.parentNode.previousSibling.previousSibling.style.display = 'block';
			setTimeout(function(){
				obj.parentNode.previousSibling.previousSibling.style.webkitTransform = 'translateX(0px)';
			}, 1); 
		}, 1000);
	}
</script>";
startPage($title, $meta_key, $meta_desc, null, $morejava);
if (!$_REQUEST['ministry']){
	printf("<p>Missing ministry parameter...</p>");
	return 0;
} else {
	$rawResult = mysql_query("SELECT * FROM `ministryApps` WHERE `ministry`='".$_REQUEST['ministry']."'");
	if (mysql_num_rows($rawResult) == 0){
		printf("<p>Ministry does not exist...</p>");
	} else {
		$ministry = mysql_fetch_array($rawResult);	
	}
}
page_title_no_content($ministry['ministry']." Ministry Questionnaire");
printf("<div class='content' style=''>\n");
if ($_POST){
	postToDB();
	$message .= $_POST['fname']." ".$_POST['lname']."<br>";
	$message .= "Age: ".$_POST['age']."<br>";
	$message .= "<a href='".$_POST['email']."'>".$_POST['email']."</a><br>";
	$message .= "Cell: ".$_POST['cellPhone']."<br>";
	$message .= "Home:".$_POST['homePhone']."<br><br><br>";
	for ($x=0;$x<(count($_POST)-6);$x++){
		if (!empty($ministry["$x"])){
			$message .= "<b>".$ministry["$x"]."</b><br>".$_POST["$x"]."<br><br>";
		}
	}
	$x = mail("codys@southhillcalvary.org, ".$ministry['contact'], "New Application", stripslashes($message), 'From: application@southhillcalvary.org'."\r\n".'MIME-Version: 1.0'."\r\n".'Content-type: text/html;'."\r\n");
	if ($x){
		printf("\t<br>Thank you for taking the time to apply, we will review your application shortly.<br>\n");
		printf("</div>\n");
		end_page_title();
		end_body();
		return 0;
	} else {
		printf("\tSorry, there was an error with your application, please try resubmitting.<br><br>\n");
	}
}
printf("\t<p>%s</p><br><br>\n", $ministry['welcomeMessage']);
printf("\t<form class='questions' method='post'>\n");
printf("\t\t<div class=''>\n");
printf("\t\t\t<h4>Personal Info</h4><br>\n");
printf("\t\t\t<input type='text' style='%s' placeholder='First Name' name='fname' value='%s'> \n","98%", $_POST['fname']);
printf("\t\t\t<input type='text' style='%s' placeholder='Last Name' name='lname' value='%s'>\n","98%", $_POST['lname']);
printf("\t\t\t<input type='number' style='%s' placeholder='Age' name='age' value='%s'><br><br>\n","98%", $_POST['age']);
printf("\t\t\t<input type='text' style='%s' maxlength='12' placeholder='Home Phone' name='homePhone' value='%s'>\n","98%", $_POST['homePhone']);
printf("\t\t\t<input type='text' style='%s' maxlength='12' placeholder='Cell Phone' name='cellPhone' value='%s'>\n","98%", $_POST['cellPhone']);
printf("\t\t\t<input type='text' style='%s' name='email' placeholder='Email' onkeyup='validateEmail(this)' value='%s'><br><br>","98%", $_POST['email']);
printf("</div>\n");
for ($x=0;$x<((mysql_num_fields($rawResult)-4)/2);$x++){
	if (empty($ministry["$x"])){
		continue;
	}
	printf("<div class=''>\n");
	question($ministry["$x"], $x, $ministry);
	printf("</div>\n");
}
printf("<button onclick='event.preventDefault();customSubmit(this.parentNode);' value='1'>Submit</button>\n");
printf("\t</form>\n");
printf("\t<span style='color:red;' id='incomplete'></span>\n");
printf("</div>\n");
endPage();
?>